<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="新闻类型" prop="type">
        <el-select v-model="queryParams.newsType" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in newsTypeOps"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户端" prop="type">
        <el-select v-model="queryParams.showClient" placeholder="请选择客户端" clearable size="small">
          <el-option
            v-for="dict in showClientOps"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="跳转方式" prop="type">
        <el-select v-model="queryParams.urlType" placeholder="请选择跳转方式" clearable size="small">
          <el-option
            v-for="dict in jumpTypeOps"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间" prop="pubTime">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.pubTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择发布时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['cms:news:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['cms:news:edit']"
        >修改</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newsList" >
      <el-table-column label="ID" align="center" prop="newsId" v-if="false"/>
      <el-table-column label="缩略图" align="center" prop="thumbnailImg" >
        <template slot-scope="scope">
          <el-image :src="ossPreview + scope.row.thumbnailImg" style="width: 100px"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="禁用状态" align="center" prop="delFlag" :formatter="delFlagFormat"/>
      <el-table-column label="新闻类型" align="center" prop="newsType" :formatter="newsTypeFormat"/>
      <el-table-column label="客户端" align="center" prop="showClient" :formatter="showClientFormat"/>
      <el-table-column label="区域" align="center"  >
        <template slot-scope="scope">
          <span>{{scope.row.allArea == 1 ? '全国' : scope.row.province + ' ' + scope.row.city}}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="pubTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pubTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['cms:news:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleDisable(scope.row)"
            v-hasPermi="['cms:news:remove']"
            v-if="scope.row.delFlag == 0"
          >禁用</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleEnable(scope.row)"
            v-hasPermi="['cms:news:remove']"
            v-if="scope.row.delFlag == 1"
          >启用</el-button>
          <el-button size="mini"
                     type="text"
                     class="btn"
                     @click="copyLink" data-clipboard-action="copy"
                     :data-clipboard-text="pathpre + scope.row.newsId">
            复制链接
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改新闻公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="新闻类型" prop="type">
              <el-select v-model="form.newsType" placeholder="请选择类型" clearable size="small">
                <el-option
                  v-for="dict in newsTypeOps"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跳转类型" prop="type">
              <el-select v-model="form.urlType" placeholder="请选择类型" clearable size="small">
                <el-option
                  v-for="dict in jumpTypeOps"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="客户端" prop="showClient">
              <el-select v-model="form.showClient" placeholder="请选择客户端" clearable size="small">
                <el-option
                  v-for="dict in showClientOps"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行政区划" prop="name">
              <el-cascader
                ref="cascaderAddr"
                size="medium"
                v-model="areaArr"
                :options="areaoptions"
                @change="handleAddressFun"></el-cascader>
              <el-checkbox v-model="checked" @change="allAreaChange">全国</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布时间" prop="pubTime">
              <el-date-picker clearable size="small" style="width: 200px"
                              v-model="form.pubTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择发布时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="内容" v-if="form.urlType == 2">
          <tinymce v-model="form.content" :height="300"/>
        </el-form-item>
        <el-form-item label="缩略图" prop="thumbnailImg">
          <dropzone id="myVueDropzone" :url="url"  :defaultImg="defaultImg" @dropzone-removedFile="dropzoneR" @dropzone-success="dropzoneS" />
        </el-form-item>

        <el-form-item label="链接" prop="url" v-if="form.urlType == 4">
          <el-input v-model="form.url" placeholder="请输入外部链接地址" />
        </el-form-item>
        <el-form-item label="AppId" prop="appid" v-if="form.urlType == 5">
          <el-input v-model="form.appid" placeholder="请输入跳转小程序的appid" />
        </el-form-item>
        <el-form-item label="页面地址" prop="path" v-if="form.urlType == 5 || form.urlType == 3">
          <el-input v-model="form.path" placeholder="请输入小程序页面地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listNews, getNews, delNews, addNews, updateNews, exportNews,chgEnable } from "@/api/cms/news";
  import { cascaderCity} from "@/api/cms/region";
  import Tinymce from '@/components/Tinymce'
  import Dropzone from '@/components/Dropzone'
  import {mapGetters} from "vuex";
  import defaultSettings from '@/settings'
  import Clipboard from "clipboard";
  export default {
    name: "News",
    components: { Tinymce,Dropzone },
    data() {
      return {
        ossPreview: defaultSettings.ossPreview,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 新闻公告表格数据
        newsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 删除状态   0未删除   1 已删除字典
        delFlagOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: null,
          newsType: null,
          showClient: null,
          content: null,
          pubTime: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        },
        visible: false,
        url:process.env.VUE_APP_BASE_API + '/common/upload/oss',
        defaultImg:'',
        num: 0,
        successNum: 0,
        fileList: [],
        newsTypeOps:[],
        showClientOps:[],
        jumpTypeOps:[],
        pathpre: 'pages/cms/news-detail?news=',
        areaoptions: [],
        areaArr:[],
        checked: false
      };
    },
    computed: {
      ...mapGetters(['token']),
      headers() {
        return{
          "Authorization": this.token // 直接从本地获取token就行
        }
      }
    },
    created() {
      this.getList();
      this.getDicts("sys_is_enable").then(response => {
        this.delFlagOptions = response.data;
      });
      this.getDicts("news_type").then(response => {
        this.newsTypeOps = response.data;
      });
      this.getDicts("show_client").then(response => {
        this.showClientOps = response.data;
      });
      this.getDicts("news_jump_type").then(response => {
        this.jumpTypeOps = response.data;
      });
      this.areaCascader();
    },
    methods: {
      areaCascader() {
        cascaderCity().then(res => {
          this.areaoptions = res.data;
        })
      },
      /** 查询新闻公告列表 */
      getList() {
        this.loading = true;
        listNews(this.queryParams).then(response => {
          this.newsList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 删除状态   0未删除   1 已删除字典翻译
      delFlagFormat(row, column) {
        return this.selectDictLabel(this.delFlagOptions, row.delFlag);
      },
      newsTypeFormat(row, column) {
        return this.selectDictLabel(this.newsTypeOps, row.newsType);
      },
      showClientFormat(row, column) {
        return this.selectDictLabel(this.showClientOps, row.showClient);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          newsId: null,
          title: null,
          content: null,
          thumbnailImg: null,
          pubTime: null,
          delFlag: null,
          showClient: 0,
          province:'',
          provinceCode:'',
          city:'',
          cityCode:'',
          allArea: 0,
          sort: 1,
          newsType: 1,
          url:'',
          urlType: 1,
          appid: '',
          path: '',
          createTime: null,
          updateTime: null
        };
        this.checked = false;
        this.areaArr = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加新闻公告";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const newsId = row.newsId || this.ids
        getNews(newsId).then(response => {
          this.form = response.data;
          this.areaArr[0] = this.form.provinceCode;
          this.areaArr[1] = this.form.cityCode;
          this.checked = this.form.allArea == 0 ? false : true;
          this.defaultImg = this.ossPreview + this.form.thumbnailImg;
          this.open = true;
          this.title = "修改新闻公告";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.allArea == 1){
              this.form.provinceCode = '';
              this.form.cityCode = '';
              this.form.province = '';
              this.form.city = '';
            }else{
              if (!this.form.city){
                this.msgError("请选择行政区划");
                return;
              }
            }
            if (this.form.newsId != null) {
              updateNews(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addNews(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleEnable(row) {
        const newsIds = row.newsId || this.ids;
        this.$confirm('是否确认启用新闻公告编号为"' + newsIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return chgEnable(newsIds,0);
        }).then(() => {
          this.getList();
          this.msgSuccess("修改成功");
        }).catch(function() {});
      },
      handleDisable(row) {
        const newsIds = row.newsId || this.ids;
        this.$confirm('是否确认禁用新闻公告编号为"' + newsIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return chgEnable(newsIds,1);
        }).then(() => {
          this.getList();
          this.msgSuccess("修改成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有新闻公告数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportNews(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      },
      dropzoneS(file,xhr) {
        this.form.thumbnailImg = xhr.imgUrl;
        this.defaultImg = xhr.imgUrl;
        this.$message({ message: 'Upload success', type: 'success' })
      },
      dropzoneR(file) {
        console.log(file.xhr.response.data)
        this.$message({ message: 'Delete success', type: 'success' })
      },
      copyLink () {
        let clipboard = new Clipboard('.btn')
        clipboard.on('success', e => {
          this.msgSuccess("复制成功");
          clipboard.destroy() // 使用destroy可以清楚缓存
        })
        clipboard.on('error', e => {
          this.msgError("复制失败");
          clipboard.destroy()
        })
      },
      handleAddressFun: function(value){
        console.log(value)
        var node = this.$refs['cascaderAddr'].getCheckedNodes()[0];
        var  thsAreaCode = node.pathLabels   //注意2： 获取label值
        console.log(thsAreaCode)
        this.form.provinceCode = value[0];
        this.form.cityCode = value[1];
        this.form.province = thsAreaCode[0];
        this.form.city = thsAreaCode[1];
      },
      allAreaChange(val){
        console.log('全国：' + val)
        if (val){
          this.form.allArea = 1;
        }else{
          this.form.allArea = 0;
        }
      }
    }
  };
</script>
